<?php

namespace api\zhengmao\middleware;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class CheckToken
{
    public function handle($request, \Closure $next)
    {
        $header = request()->header();
        if (!isset($header['token']) || empty($header['token'])) {
            return json(['code' => 0, 'msg' => '缺少token'], );
        }
        $key = new Key(config('app.Jwt_key'), 'HS256');
        try {
            $res = JWT::decode($header['token'], $key);
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => $e->getMessage()],);
        }
        $request->userID = $res->data->user_id;
        return $next($request);
    }
}